// GimmeCantonese!Jimmy (GC!J) User Script
// Version 0.4 Beta
// 1-September-2008
// Release under GPL license
// http://www.gnu.org/copyleft/gpl.html
// Cantonese gif Images Code to HKSCS list by Clement T (http://chiunam.net/)
// Released under Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. (http://creativecommons.org/licenses/by-nc-sa/2.5/)
//
// Contributors:
// Clement T (http://chiunam.net)         Script maintainence
// Jackysee (http://jacky.seezone.net/)   Significantly improve the inital functionality of this script
// ChainsawRiot (http://blog.tiney.com)   Proof of concept
// ------------------------------------------------------------------------
// The Rage/Readme:
// 既然用得這個Script，你都識得看中文，我又無謂連個Readme寫英文了。
// 蘋果日報網/壹傳網使用圖像來表示廣東話字。
// 有些廣東字可以用「o下」表示，或者直接用廣東字「吓」。出來個效果會正好多，對吧？
// 這個User script 就是將那些圖像轉成文字，同時移除中文字間的空格，那 Copy and Paste
// 時就會完整Copy所有字。
//
// ------------------------------------------------------------------------
//
// This is a Greasemonkey user script.  To install it, you need
// Firefox 3.0 or later (http://www.getfirefox.com/ and
// Greasemonkey 0.3 or later: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "GimmeCantonese!Jimmy", and click Uninstall.
//
// ------------------------------------------------------------------------
//
// change log
// 0.4 - fixed the buttons clicking issues of the images on the left hand side
// 0.3 - separate the character code to another script
// 0.2 - move the script to google code
// 0.1 - initial release
//
// -------------------------------------------------------------------------
// ==UserScript==
// @name		GimmeCantonese!Jimmy
// @namespace	http://code.google.com/p/gcj/
// @description	Ask Jimmy to Give u Genuine Cantonese Display in atnext.com
// @include		http://*.atnext.com/*
// @include     http://*.appleactionews.com/*
// @include     http://*.appleactionnews.com/*
// ==/UserScript==


//Get the Character Code from Google Code
GM_xmlhttpRequest({
	method: 'GET',
	url: 'http://gcj.googlecode.com/svn/trunk/gcjcharcode.js',
	headers: {
        	'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        	'Accept': '*/*',
    },
	onload: function(responseDetails) {
		if (responseDetails.status == 200) {
			eval(responseDetails.responseText);

			//Replace the Hong Kong character images
			var images = document.evaluate(
				"//img[@src][@align='absmiddle']",
				document,
				null,
				XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
				null);
			for (var i = 0; i < images.snapshotLength; i++) {
				var img = images.snapshotItem(i);
				var num = img.src.replace(/.*\/new_hkfont\/.*\/([a-zA-Z0-9]{2,7})\.gif/i,"$1");
				if(num && gcjCharCodes[num]){
					var replacement = document.createTextNode(gcjCharCodes[num]);
					img.parentNode.replaceChild(replacement,img);
				}
			}

			//Toogle Chinese spaces
			manipulate_chinese_spaces();

			//Add Logo
			addLogo();
		} else {
			alert('GC!J error on fetching character code:\n\n' +
			responseDetails.status + ' ' + responseDetails.statusText);
		}
	},
	onerror: function(responseDetails) {
		alert('GC!J error on fetching character code:\n\n' +
		responseDetails.status + ' ' + responseDetails.statusText);
	}
});


//Function for adding GlobalStyle
function addGlobalStyle(css) {
	var head, style;
	head = document.getElementsByTagName('head')[0];
	if (!head) { return; }
	style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = css;
	head.appendChild(style);
}


//Function for adding GC!J logo
function addLogo() {
	var logo = document.createElement('img');
	logo.src = 'data:image/png;base64,' +
			'iVBORw0KGgoAAAANSUhEUgAAAFAAAAAPCAIAAAD8q9/YAAAB6UlEQVRIieVXTyiDYRx+3s9HHGT+tGnW' +
			'MkoOCMXBhUJKDqNYKQfKpignzEUkF1dSS3LjIicXUkKtHGYYK8tJ/l5Eo2T7vA6b7d2++XxfG1Oe0/v7' +
			'vd/v6Xl6n/etj5jNZvwn8ABsNluyZfwSLBYLHyoopQAE6uO5NEqp9+0+M01DCJGm+PaDv4OAQe6zeHfc' +
			'rcwf1s/YS9Y9w3cvZxsX1qTK+ykEDb9TITfDUKU2laoa75/da+eDmen5BzdLr/6n5OpLOIKRTuFSC5/y' +
			'DX3L9OyYlFdvdfG1u/u3rV5PU06FukMmVyAzYHIe6LBl1BUQd74d/GpEJsJ3GH4BV5dw3/o9riL/qUpv' +
			'yJq2Eq0RallEEmaUSow5GKfPEBjDhmKosnHi5MeGigGUVWJ4HLvbaGhWpBWilywhQgkhCfHMGH58AM9j' +
			'cQ6Ts7DvQa3Bixd58s43UlZUMyQ0zuOKSa4UXHi5tIDuXlxfQqfHziZq6rC+CmOnIjWsE3GHveRRW9JU' +
			'7JYSdzHAGC6vgusIRhMGeqDRYmoUPf0o0MvnIoSIw8x2otYS6qUH5UsSg4l0SxtcThw70N6F9Az4fFBl' +
			'x0P9N8FHVCMTuLkCAEEAx0GrS4qmH0XYcPBd0eoABEIjJzrxvyK/DPLf/pY+AIEayJJDb1g6AAAAAElF' +
			'TkSuQmCC';
	logo.setAttribute('style','position:absolute;top:0;left:0;');
	document.body.insertBefore(logo, document.body.firstChild);
}


//Toogle spaces between Chinese characters
const key = "NoChineseSpaces"

manipulate_chinese_spaces = function(){
	var xpath = new Array (
					"//h2[@class='article_title']",
					"//div[@class='article_0pic']/h3",
					"//p[@class='article_content']",
					"//p[@class='captions']",
					"//td[@class='bigbox_title']",
					"//div[@class='article']"
				);

	if (GM_getValue(key, true)){

		for (var i=0; i<xpath.length; i++){

			var els = document.evaluate( xpath[i], document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );

			for (var j=0; j<els.snapshotLength; j++) {
				var el = els.snapshotItem(j);
				el.innerHTML = el.innerHTML.replace(/([\u0000-\u00FF] )* *([^\u0000-\u00FF])/g,"$1$2");
			}

		}		

		addGlobalStyle( 'p.article_content, p.captions { line-height: 1.5 !important; }' );					


	} else {

		for (var i=0; i<xpath.length; i++){

			var els = document.evaluate( xpath[i], document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );			

			for (var j=0; j<els.snapshotLength; j++) {
				var el = els.snapshotItem(j);
				el.innerHTML = el.innerHTML.replace(/([^\u0000-\u00FF])([^\u0000-\u00FF])/g,"$1 $2");
				el.innerHTML = el.innerHTML.replace(/([^\u0000-\u00FF])([^\u0000-\u00FF])/g,"$1 $2");
			}

		}

		addGlobalStyle( 'p.article_content, p.captions { line-height: normal !important; }' );

	}
};

toogle_setting = function(){
	GM_setValue(key, !GM_getValue(key, true));
	manipulate_chinese_spaces();
}

GM_registerMenuCommand("Toogle Chinese Spaces", toogle_setting, "j", "shift alt", "t");
